const WebSocket = require('ws'); //爬虫//如果该用户是第一位用户
const zlib = require('zlib');
////
class socketClient {
  constructor(url) {
    this.url = url;
    this.socket = new WebSocket(url, [], {
      headers: {}
    });
    this.reqQueue = [];
    //初始化socket向爬虫订阅(sub)的数组
    this.initial_req_arr = [];
    this.arr_sub = [];
    this.prev_all_socket_arr_sub = [];
    this.all_socket_arr_sub = ['market.overview'];
  }
  onerror() {
    this.socket.on('error', err => {
      console.error('Websocket err:' + err);
    });
  }
  onopen() {
    this.socket.on('open', () => {
      console.log('爬虫正在爬取火币数据....');
      this.socket.send(JSON.stringify({ sub: 'market.overview' }));
      this.all_socket_arr_sub.forEach(item => {
        this.socket.send(JSON.stringify(item));
      });
      //请求req
      this.initial_req_arr.forEach(item => {
        this.socket.send(JSON.stringify(item));
      });
      //心跳检测
      let check_alive = setInterval(() => {
        this.reqQueue.forEach(socket => {
          //ping客户端
          socket.emit('ping', { ping: new Date().getTime() });

          //判断ping的次数和是否得到回应
          if (socket.check_times > 3) {
            if (socket.pong_data === 'pong') {
              console.log('aaaa');
              //删除失去响应的用户
              this.reqQueue = this.reqQueue.filter(item => {
                if (item.id === socket.id) {
                  return false;
                } else {
                  return true;
                }
              });
              if (this.reqQueue.length === 0) {
                clearInterval(check_alive); //取消定时器
              }
              console.log(
                `用户${socket.id}失去响应 目前在线人数${this.reqQueue.length}人`
              );
            } else {
              socket.pong_data = 'pong';
              socket.check_times = 0;
            }
          } else {
            if (socket.pong_data !== 'pong') {
              console.log(socket.id + '回应了我');
              socket.pong_data = 'pong';
              socket.check_times = 0;
            } else {
              socket.check_times++;
            }
          }
        });
      }, 5000);
    });
  }
  onclose() {
    this.socket.on('close', () => {
      console.warn('当前没有用户,暂停爬取!');
    });
  }
  onmessage() {
    this.socket.on('message', msg => {
      //向火币服务器订阅消息
      // if (
      //   this.prev_all_socket_arr_sub.length < this.all_socket_arr_sub.length
      // ) {
      //   // console.log(this.all_socket_arr_sub, 'aaaa');
      //   // console.log(this.prev_all_socket_arr_sub, 'bbb');
      //   for (
      //     let i = this.prev_all_socket_arr_sub.length;
      //     i < this.all_socket_arr_sub.length;
      //     i++
      //   ) {
      //     ;
      //     console.log(`向huobi发起新的${this.all_socket_arr_sub[i].sub}订阅`);
      //     //
      //   }
      //
      // }

      //检查有没有用户
      console.warn(this.reqQueue.length);
      if (this.reqQueue.length === 0) {
        this.close();
      }

      zlib.unzip(msg, (err, buf) => {
        if (err) {
          console.log(err);
        } else {
          let msg_str = buf.toString();
          if (msg_str.indexOf('ping') !== -1) {
            //向火币发送pong

            this.socket.send(
              JSON.stringify({ pong: Math.round(new Date().getTime()) }),
              {},
              err => {
                if (err) {
                  console.log(err);
                }
              }
            );
          } else {
            let oMsg = JSON.parse(msg_str);
            let msg_name = oMsg.ch;
            // if (!msg_name) {
            //   console.log(msg_str);
            // }
            this.reqQueue.forEach(socket => {
              //发送detail
              //收到sub请求的回应
              if (
                msg_name &&
                (msg_name.indexOf('detail') !== -1 ||
                  msg_name.indexOf('depth.step') !== -1 ||
                  msg_name.indexOf('view') !== -1 ||
                  msg_name.indexOf('depth.percent10') !== -1 ||
                  msg_name.indexOf('kline') !== -1)
              ) {
                console.log(msg_name + '收到消息');
                socket.arr_sub &&
                  socket.arr_sub.forEach(item => {
                    if (
                      item.sub === msg_name ||
                      msg_name.indexOf('view') !== -1
                    ) {
                      console.log(`向:${socket.id} 发送了一条${msg_name}消息`);
                      socket.emit(msg_name + '.sub', msg_str);
                    }
                  });
                // console.log(this.all_socket_arr_sub, 'all_socket_sub');
              } else {
                //收到req请求的huiying
                if (socket.req_arr) {
                  socket.req_arr.forEach(item => {
                    if (item.req === oMsg.rep) {
                      socket.emit(oMsg.rep + '.req', oMsg);
                      console.log(oMsg.rep + '.req', 8888888888888);
                    }
                  });
                }
              }
            });

            // if (msg_name === 'market.btcusdt.depth.step0') {
            //   console.log(JSON.parse(msg_str));
            // }
          }
        }
      });
    });
  }
  close() {
    this.socket.close();
  }
}
module.exports = socketClient;
